#include <iostream>
#include <vector>
#include <pthread.h>
#include <unistd.h>

pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;

void* MCore(void* args)
{
    sleep(3);
    std::cout << "master 开始工作" << std::endl;
    std::string name = static_cast<char*>(args);
    while(1)
    {
        pthread_cond_signal(&gcond);//唤醒其中一个队列首部的线程
        std::cout << "master唤醒一个线程" << std::endl;
        sleep(1);
    }
        
}
void StartMaster(std::vector<pthread_t>* threads)
{
    pthread_t tid;
    int n = pthread_create(&tid,nullptr,MCore,(void*)"Master Thread");
    if(n == 0)
    {
        std::cout << "create master success" << std::endl;
    }
    threads->emplace_back(tid);
}

void* SCore(void* args)
{
    std::string name = static_cast<char*>(args);
    while(1)
    {
        //1.加锁
        pthread_mutex_lock(&gmutex);
        //2.条件变量
        pthread_cond_wait(&gcond,&gmutex);
        std::cout << "当前被唤醒的线程是：" << name << std::endl;
        sleep(1);
        
        //3.解锁
        pthread_mutex_unlock(&gmutex);
        
    }

}
void StartSlaver(std::vector<pthread_t>* threads,int n)
{
    for(int i = 0;i < n;++i)
    {
        char* name = new char[64];
        snprintf(name,64,"new thread-%d",i+1);
        pthread_t tid;

        int n = pthread_create(&tid,nullptr,SCore,(void*)name);
        if(n == 0)
        {
            std::cout << "create success:" << name << std::endl;
            threads->emplace_back(tid);
        }
    }
}

void WaitThread(std::vector<pthread_t>& threads)
{
    for(auto& tid: threads)
    {
        pthread_join(tid,nullptr);
    }
}
int main()
{
    std::vector<pthread_t> threads;
    StartMaster(&threads);
    StartSlaver(&threads,5);
    WaitThread(threads);

    return 0;
}